<template>
   
    <el-form label-width="100px" ref="ruleFormRef" :model="supinfo" :rules="rules" class="demo-ruleForm" status-icon>
      <el-form-item label="SPU名称" prop="spuName">
        <el-input placeholder="请输入SPU名称" v-model="supinfo.spuName" />
      </el-form-item>
      <el-form-item label="品牌" prop="tmId">
        <el-select placeholder="请选择品牌" v-model="supinfo.tmId">
          <el-option :label="trademark.tmName" :value="trademark.id" v-for="trademark in trademarklist"
            :key="trademark.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input type="textarea" :rows="2" v-model="supinfo.description" />
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <div>
          <el-upload :action="`${BASE_URL}/admin/product/upload`" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload" list-type="picture-card" :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full style="margin:auto;display:block" :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </div>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select placeholder="请选择销售属性" v-model="supinfo.spuSaleAttr">
          <el-option :label="basesaleattr.name" :value="basesaleattr.name" v-for="basesaleattr in filterspuSaleAttr"
            :key="basesaleattr.id" />
        </el-select>
        <el-button type="primary" :icon="Plus" style="margin-left: 15px;" :disabled="!supinfo.spuSaleAttr"
          @click="addspusaleattr">添加销售属性</el-button>
      </el-form-item>
      <el-table border style="margin:16px 0;" :data="supinfo.spuSaleAttrList">
        <el-table-column label="序号" type="index" align="center" width="80"></el-table-column>
        <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
        <el-table-column label="属性值名称列表">
          <template v-slot="{ row }">
            <el-tag v-for="(tag, index) in row.spuSaleAttrValueList" :key="tag" class="mx-1" closable
              :disable-transitions="false" style="margin-left: 5px;" @close="handleClose(row, index)">
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input style="width:60px;" v-if="row.inputVisible" ref="InputRef" v-model="inputValue" class="ml-1 w-20"
              size="small" @keyup.enter="handleInputConfirm(row)" @blur="handleInputConfirm(row)" />
            <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(row)" style="margin-left: 5px;">
              + New Tag
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row, $index }">
            <el-popconfirm :title="`您真的要删除${row.saleAttrName}属性值吗?`" @confirm="delinfovalue(row, $index)">
              <template #reference>
                <el-button title="删除属性" type="danger" :icon="Delete" size="small"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary">保存</el-button>
      <el-button>取消</el-button>
    </el-form>
</template>

<script lang="ts">
    export default {
        name:'Spufrom'
    }
</script>

<script setup lang="ts">
import {onMounted, ref,reactive, computed,nextTick} from 'vue'
import { Plus ,Delete} from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile ,FormRules,FormInstance} from 'element-plus'
import {ElMessage,ElInput } from 'element-plus'
import {reqgettrademarklist,reqgetbasesaleattrlist} from '@/api/Product/Spu'
import type {trademarklistmodul,basesaleattrlistmodul,supinfodatamodul,spuSaleAttrListmodul,spuSaleAttrmodul} from '@/api/Product/model/Spu'
import usercategorylist from '@/stores/category'
// 定义导航数据库
let categorylist = usercategorylist()

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
// 页面挂载请求数据
let trademarklist = ref<trademarklistmodul>([])
let basesaleattrlist = ref<basesaleattrlistmodul>([])
onMounted( async () => {
  try {
    let [reqtrademarklist,reqbasesaleattrlist] = await Promise.all([reqgettrademarklist(),reqgetbasesaleattrlist()])
    trademarklist.value =reqtrademarklist
    basesaleattrlist.value =reqbasesaleattrlist
    
} catch (error) {
    ElMessage.error('请求品牌数据或者销售列表失败')
  }
})

//定义表单数据，以后作为提交请求体参数
let supinfo = reactive<supinfodatamodul>({
    category3Id: categorylist.categorySelectorid3,//三级ID
    description: '',//描述
    spuImageList: [],//图片数组
    spuName:'',//spu名字
    spuSaleAttrList:[],//属性名数组
    spuSaleAttr:undefined,
    tmId:undefined//品牌名称
})


// 表单尺寸
const formSize = ref('default')
// 表单唯一标识
const ruleFormRef = ref<FormInstance>()
// 图片上传路径
let BASE_URL = import.meta.env.VITE_API_URL
// 表单验证
const rules = reactive<FormRules>({
    spuName: [
    { required: true, message: 'spu名字不能为空', trigger: 'blur' },
  ],
  spuImageList: [
    {
      required: true,
      message: '至少一张上传图片',
      trigger: 'change',
    },
  ],
  description: [
    {
      required: true,
      message: '描述不能为空',
      trigger: 'change',
    },
  ],
  spuSaleAttrList: [
    {
      required: true,
      message: '属性名不能为空',
      trigger: 'blur',
    },
  ],
  tmId: [
    {
      required: true,
      message: '品牌不能为空',
      trigger: 'change',
    },
  ],
})
// 上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = ( response,uploadFile) => {
    supinfo.spuImageList.push({
        imgName: uploadFile.name,
         imgUrl: response.data,
    })
    console.log(response,uploadFile);
    
}
// 上传图片校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  let logoUrltyoelist = ['image/jpeg','image/png','image/png','image/webp']
  if (!logoUrltyoelist.includes(rawFile.type)) {
    ElMessage.error('图片格式为jpg/png/png/webp')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片最大为2MB!')
    return false
  }
  return true
}
// 确认添加属性名
let addspusaleattr = ()=>{
    supinfo.spuSaleAttrList.push({
        inputVisible:false,
        saleAttrName : supinfo.spuSaleAttr as string ,
        spuSaleAttrValueList:[],
    })
    supinfo.spuSaleAttr = ''
}
// 定义一个计算属性如果选中一个下拉少一个
let filterspuSaleAttr = computed(() => {
    return (
        basesaleattrlist.value.filter((item)=>{
            return  !supinfo.spuSaleAttrList.find(item1 => item1.saleAttrName === item.name)
        })
    )
})
// 删除属性名
  let delinfovalue = (row:spuSaleAttrListmodul,index:number)=>{
    supinfo.spuSaleAttrList.splice(index,1)
    ElMessage.success(`删除${row.saleAttrName}属性值成功`)
  }
// 属性值标签
const inputValue = ref('')
const dynamicTags = ref(['Tag 1', 'Tag 2', 'Tag 3'])
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()
// 点击叉号移除
const handleClose = (row:spuSaleAttrListmodul,index:number) => {
    console.log(index);
    
  row.spuSaleAttrValueList.splice(index,1)
}
// 单击显示输入框
const showInput = (row:spuSaleAttrListmodul) => {
  row.inputVisible = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}
// 失去光标以后变成标签
const handleInputConfirm = (row:spuSaleAttrListmodul) => {
  if (inputValue.value) {
    row.spuSaleAttrValueList.push({
        saleAttrValueName:inputValue.value,
        saleAttrName:row.saleAttrName as string,
        isChecked:'0'
    })
  }
  row.inputVisible = false
  inputValue.value = ''
}

</script>

<style lang="scss" scoped>
.ml{
    margin-left: 20px;
}
</style>